<template>
  <div class="map-container">
    <div id="map-container"></div>
    <lines
      v-show="linesDialog"
      @pointClick="pointClick"
      @pointcancel="pointcancel"
    ></lines>
    <template v-if="showMaker">
      <!-- <MakerDetail :prop1='3000'></MakerDetail> -->
    </template>
  </div>
</template>

<script>
import lines from "@/components/Map/lines.vue";
import FenceGeo from "@/components/Map/FenceGeo.vue";
import makerdetail from "@/components/Map/makerdetail.vue";
import "jquery";
import layer from "layui-layer";
import {
  setMeasureToolTip,
  setDrawlatlngToolTip,
  setDrawGeofencingToolTip,
  pointPositionCalc,
  getCurentTime,
  getStringByLatlng,
  getLatlngByString,
  getPopupContent,
} from "@/utils/maptools.js";
import {
  bearing,
  destination,
  point,
  lineString,
  featureCollection,
} from "@turf/turf";
import mappointjson from "@/assets/data/point.geojson";
// import maplinesjson from "@/assets/data/lines.geojson";
import maplinesjson from "@/assets/data/lines_test.geojson";
//import maplines12json from "@/assets/data/lines12.geojson";
import { listBgeoinfo } from "@/api/invoice/geoinfo";

export default {
  name: "map-point",
  components: { FenceGeo, lines },
  data() {
    return {
      map: null,
      option: {
        minZoom: 11,
        maxZoom: 21,
        center: [33.747319, 113.33041],
        crs: L.CRS.EPSG3857,
        zoom: 17,
        zoomControl: false, // 禁用 + - 按钮
        doubleClickZoom: true, // 禁用双击放大
        attributionControl: false, // 移除右下角leaflet标识
        dragging: true, // 禁止鼠标拖动滚动
        boxZoom: true, // 决定地图是否可被缩放到鼠标拖拽出的矩形的视图，鼠标拖拽时需要同时按住shift键.
        scrollWheelZoom: true, // 禁止鼠标滚动缩放
        //preferCanvas: true, // 使用canvas模式渲染矢量图形
        rotate: true,
				touchRotate: true,
				rotateControl: {
					closeOnZeroBearing: false
				},
				bearing: 0,
      },
      overLayer: {
        polylines: [],
        polygons: [],
        measurements: [],
        fonts: [],
      },
      tempGp: {
        lineNode: [],
        lineNodeLen: 0,
        tempLine: null,
        polygonNode: [],
        polygonNodeLen: 0,
        tempNode: [],
        tempPolygon: null,
        fontsNode: [],
      },
      linesdata: null,
      pointdata: null,
      linesdata12: null,
      // 绘制工具类型：测量、围栏等等
      drawArr: [],
      drawTools: {
        measureDisTool: null, //测距工具
        measureAreaTool: null, //测面工具
        polyGeofencing: null, //多边形围栏
        rectGeofencing: null, //矩形围栏
        circleGeofencing: null, //圆形围栏
        markerGeofencing: null, //点
        geofencingEdit: null, //编辑围栏
        geofencingDel: null, //删除围栏
        geofencingOptions: {}, //关闭围栏选项
        editedGeoLayer: [], //编辑过的地理围栏图层数组
        drawToolType: "", //绘制类型
      },
      layerGroup: {
        linesLayerGroup: null, // 线路图层组
        pointsLayerGroup: null, // 站点图层组
        fontsLayerGroup: null, // 文字描述图层组
        signalLayerGroup: null, // 信号灯图层组
        insulatedLayerGroup: null, // 绝缘线图层组
        locomotiveLayerGroup: null, // 机车图层组
        geofencingLayerGroup: null, // 围栏图层组
        persionLayerGroup: null, // 人员图层组
        otherLayerGroup: null, // 其他图层组
        measureLayersGroup: null, // 绘制图层组
      },
      geoDialog: false, //围栏窗口
      linesDialog: false, //线路窗口
      locomotiveDialog: false, //机车窗口
      persionDialog: false, //人员窗口
      form: {
        name: "",
        geoType: "",
      },
      showMaker: false,
    };
  },
  destroyed() {
    window.removeEventListener("resize", this.changeDivHeight, false);
  },
  created() {
    //this.socketApi.getSock(this.getConfigResult);
  },
  mounted() {
    let that = this;
    window.addEventListener("resize", that.changeDivHeight);
    that.pointdata = mappointjson;
    that.linesdata = maplinesjson;
    //that.linesdata12 = maplines12json;
    this.initMap();

    this.initLines();
        // this.updateLines();
    this.initLight();
    this.initLocomotive();
    // this.initPoints();
    this.initEnclosure();
    //线路组
    //站点组
    //信号灯组
    //围栏组
    //机车组
    //人员组

    //采用图层组，存储不同类型的数据

    //初始化加载数据，中心点位置根据人员角色，可以看站，可以看全线

    //加载线路，根据规则变换线路颜色
    //加载站点，可单击看详细信息
    //加载信号灯，根据规则变换信号灯颜色

    //加载围栏，单击显示围栏信息
    //加载机车、单击显示机车信息
    //加载人员、单击显示人员信息

    //显示浮动站名信息窗口，可拖动，不影响下层地图，可单击切换看站点区域

    //地图范围变化处理元素、图形元素大小粗细、字体大小等应根据不同缩放等级变化，保证清晰可见

    //町车、盯人功能，地图跟着元素自动移动（电子地图随目标移动而平移）

    //取消町车、盯人功能，地图恢复

    //围栏功能、绘制多边形、圆形、可以删除和修改
    //一键回到当前位置或者最初位置
    //选点经纬度功能
    //选定多边形、圆形，显示经纬度功能

    //websocket ，监听机车、人员、围栏变化
    //可以实时增加机车、删除机车、机车位置矫正
    //可以增加人员、删除人员、控制人员颜色（出线红色显示，回去后恢复原颜色）
  },
  methods: {
    //初始化地图
    initMap() {
      this.map = this.$mapnew.createMap("map-container", this.option);
      this.map.allowSelfIntersection;
      var zoomControl = L.control.zoom({
        // 放大按钮的标题
        zoomOutTitle: "放大",
        // 缩小按钮的标题
        zoomInTitle: "缩小",
        // 控件位置，'topleft', 'topright', 'bottomleft', 'bottomright'
        position: "bottomleft",
      });
      let that = this;
      // 添加缩放控件到地图
      this.map.addControl(zoomControl);
      this.initDrawCtrl();
      that.changeDivHeight();
      var places = [
        {
          label: "工具",
          value: "tool",
          items: [
            {
              label: "测量",
              value: "measureTool",
              items: [
                { label: "测距", value: "measurement" },
                { label: "侧面", value: "area" },
                { label: "删除", value: "delete" },
              ],
            },
            {
              label: "取坐标",
              value: "takeCoordinates",
              items: [
                { label: "点", value: "Marker" },
                { label: "多边形", value: "Polygon" },
                { label: "矩形", value: "Rectangle" },
                { label: "圆形", value: "Circle" },
              ],
            },
          ],
        },
      ];
      let toolmenu = L.control
        .select({
          position: "topleft",
          selectedDefault: false,
          items: places,
          onSelect: function (newItemValue) {
            if (
              newItemValue == "measurement" ||
              newItemValue == "area" ||
              newItemValue == "delete"
            ) {
              that.distanceMeasurement(newItemValue);
            } else {
              that.drawShape(newItemValue, "2");
            }
          },
        })
        .addTo(this.map);
      //设置地图范围
      this.map.setMaxBounds([
        [33.93101, 112.80673],
        [33.7362, 113.50229],
      ]);
      this.map.on("zoomend", this.onZoomEnd);
      this.layerGroup.linesLayerGroup = new L.FeatureGroup().addTo(this.map); // 线路图层组
      this.layerGroup.pointsLayerGroup = new L.FeatureGroup().addTo(this.map); // 站点图层组
      this.layerGroup.fontsLayerGroup = new L.FeatureGroup().addTo(this.map); // 文字描述图层组
      this.layerGroup.signalLayerGroup = new L.FeatureGroup().addTo(this.map); // 信号灯图层组
      this.layerGroup.insulatedLayerGroup = new L.FeatureGroup().addTo(
        this.map
      ); // 绝缘线图层组
      this.layerGroup.locomotiveLayerGroup = new L.FeatureGroup().addTo(
        this.map
      ); // 机车图层组
      this.layerGroup.geofencingLayerGroup = new L.FeatureGroup().addTo(
        this.map
      ); // 围栏图层组
      this.layerGroup.persionLayerGroup = new L.FeatureGroup().addTo(this.map); // 人员图层组
      this.layerGroup.otherLayerGroup = new L.FeatureGroup().addTo(this.map); // 其他图层组
      this.layerGroup.measureLayersGroup = new L.FeatureGroup().addTo(this.map); // 测量图层组

      this.drawTools.measureDisTool =
        /*****************************************************围栏******************************************************************/
        this.drawTools.polyGeofencing = new L.Draw.Polygon(this.map); // 多边形围栏
      this.drawTools.rectGeofencing = new L.Draw.Rectangle(this.map); // 矩形围栏
      this.drawTools.circleGeofencing = new L.Draw.Circle(this.map); // 圆形围栏
      this.drawTools.markerGeofencing = new L.Draw.Marker(this.map); // 点
      this.drawTools.geofencingEdit = new L.EditToolbar.Edit(this.map, {
        // 编辑围栏
        //绘制图层
        featureGroup: this.layerGroup.geofencingLayerGroup,
        //图形编辑控件
        edit: true,
        allowIntersection: false,
      });
      this.drawTools.geofencingDel = new L.EditToolbar.Delete(this.map, {
        // 删除围栏
        //绘制图层
        featureGroup: this.layerGroup.geofencingLayerGroup,
        //图形编辑控件
        edit: true,
        allowIntersection: false,
      });
      this.drawArr.push(
        this.drawTools.polyGeofencing,
        this.drawTools.rectGeofencing,
        this.drawTools.circleGeofencing,
        this.drawTools.markerGeofencing,
        this.drawTools.geofencingEdit,
        this.drawTools.geofencingDel
      );
      //  关闭围栏选项
      this.drawTools.geofencingOptions = {
        polygon: {
          obj: this.drawTools.polyGeofencing,
        },
        rectangle: {
          obj: this.drawTools.rectGeofencing,
        },
        circle: {
          obj: this.drawTools.circleGeofencing,
        },
        marker: {
          obj: this.drawTools.markerGeofencing,
        },
        edit: {
          obj: this.drawTools.geofencingEdit,
          editLayer: this.drawTools.editedGeoLayer,
        },
        delete: {
          obj: this.drawTools.geofencingDel,
          deleteLayer: this.layerGroup.geofencingLayerGroup,
        },
      };

      /*****************************************************测量******************************************************************/
      // 测距工具
      this.drawTools.measureDisTool = new L.Draw.Polyline(this.map, {
        // 允许折线相交
        allowIntersection: false,
        // 是否在工具提示中显示距离
        showLength: true,
        metric: ["km", "m"],
        nautic: true,
      });
      // 测面工具
      this.drawTools.measureAreaTool = new L.Draw.Polygon(this.map, {
        // 不允许多边形不相邻边相交
        allowIntersection: false,
        // 是否在工具提示中显示面积
        showArea: true,
        // ['km'，'m']的值意味着长度将以米为单位显示，当超过1000米时，以公里为单位，并且该区域将以m²或km²显示。
        metric: ["km", "m"],
        // 当不使用公制测量系统或脚时，使用nautic英里而不是码和英里
        nautic: true,
      });
      this.drawArr.push(
        this.drawTools.measureDisTool,
        this.drawTools.measureAreaTool
      );

      /************************************绘制事件处理：绘制/编辑(测量、围栏)********************************************/

      // 绘制开始：禁用掉地图双击缩放事件
      that.map.on(L.Draw.Event.DRAWSTART, function (event) {
        // 禁用掉地图双击缩放事件
        that.map.doubleClickZoom.disable();
        // 双击多边形绘制结束
        that.map.on("dblclick", function (e) {
          that.drawTools.measureAreaTool.enabled() &&
            that.drawTools.measureAreaTool.completeShape();
          that.drawTools.polyGeofencing.enabled() &&
            that.drawTools.polyGeofencing.completeShape();
        });
      });
      // 编辑-拖动：矩形、圆形
      that.map.on(L.Draw.Event.EDITMOVE, function (event) {
        if (that.drawTools.editedGeoLayer.indexOf(event.layer) === -1) {
          that.drawTools.editedGeoLayer.push(event.layer);
        }
      });
      // 编辑-缩放大小：矩形、圆形
      that.map.on(L.Draw.Event.EDITRESIZE, function (event) {
        if (that.drawTools.editedGeoLayer.indexOf(event.layer) === -1) {
          that.drawTools.editedGeoLayer.push(event.layer);
        }
      });
      // 编辑顶点：多边形
      that.map.on(L.Draw.Event.EDITVERTEX, function (event) {
        if (that.drawTools.editedGeoLayer.indexOf(event.poly) === -1) {
          that.drawTools.editedGeoLayer.push(event.poly);
        }
      });

      //绘制完成：解除地图双击缩放事件
      that.map.on(L.Draw.Event.CREATED, function (e) {
        // 图层类型
        var type = e.layerType;
        //获取绘制图层
        var drawlayer = e.layer;
        if (that.drawToolType === "measure") {
          // 测量
          var content = getPopupContent(drawlayer);
          if (content !== null) {
            drawlayer.bindPopup(content);
          }
          drawlayer.options.opacity = 1;
          drawlayer.options.weight = 2;
          that.layerGroup.measureLayersGroup.addLayer(drawlayer);
          drawlayer.openPopup();
          that.closeMeasureTools(
            that.drawTools.measureDisTool,
            that.drawTools.measureAreaTool
          );
        } else if (that.drawToolType === "pointlng") {
          let lat;
          if (e.layerType == "circle") {
            lat = e.layer._latlng + "  半径：" + e.layer._mRadius;
          } else if (e.layerType == "marker") {
            lat = e.layer._latlng;
          } else {
            lat = e.layer._latlngs[0];
          }
          that.$alert(lat, "测量");
        } else if (that.drawToolType === "geofencing") {
          that.geoDialog = true;
        }
        // 注销多边形绘制双击事件
        that.map.off("dblclick");
        // 恢复地图双击事件
        that.map.doubleClickZoom.enable();
      });

      // 删除开始
      that.map.on(L.Draw.Event.DELETESTART, function (event) {});

      // 地图点击
      that.map.on("click", function (event) {});
    },
    // 初始化绘制控件
    initDrawCtrl() {
      let that = this;
      L.easyButton(
        "<img src=" +
          require(`../../assets/images/map/huidaodangqian.png`) +
          " >",
        function (btn, map) {
          //that.drawShape("delete", "1");
        },
        "回到当前位置"
      ).addTo(that.map);
      L.easyButton(
        "<img src=" + require(`../../assets/images/map/Site.png`) + " >",
        function (btn, map) {
          that.linesDialog = true;
        },
        "站点线路"
      ).addTo(that.map);
      L.easyButton(
        "<img src=" + require(`../../assets/images/map/tongji.png`) + " >",
        function (btn, map) {},
        "统计"
      ).addTo(that.map);
    },

    //放大缩小事件处理
    onZoomEnd(e) {
      let that = this;
      let zoomlevel = that.map.getZoom();

      switch (zoomlevel) {
        case 191:
          this.setLineStyle("4");
          break;
        case 201:
          this.setLineStyle("9");
          break;
        case 211:
          this.setLineStyle("15");
          break;
        case 181:
          this.setLineStyle("3");
          break;
        case 171:
          this.setLineStyle("2");
          break;
        default:
          this.setLineStyle("1");
          break;
      }

      if (zoomlevel < 18) {
        if (that.map.hasLayer(that.layerGroup.signalLayerGroup)) {
          that.map.removeLayer(that.layerGroup.signalLayerGroup);
        } else {
          console.log("no point layer active");
        }
      }
      if (zoomlevel >= 18) {
        if (that.map.hasLayer(that.layerGroup.signalLayerGroup)) {
          console.log("layer already added");
        } else {
          that.map.addLayer(that.layerGroup.signalLayerGroup);
        }
      }
      console.log("Current Zoom Level =" + zoomlevel);
      if (zoomlevel >= 19) {
        let Layers = this.layerGroup.linesLayerGroup.getLayers();
        Layers[0].getLayers().map(function (item) {
          if (item.myTag && item.myTag == 1371699) {
            item.setStyle({ color: "red" });
          }
        });
        let Layerss = this.layerGroup.signalLayerGroup.getLayers();
        Layerss.map(function (item) {
          
        });
      }
    },
    //设置线样式
    setLineStyle(weight) {
       this.layerGroup.linesLayerGroup.setStyle({ weight: weight });
    },
    //初始化线路
    initLines() {

      console.log('d5s1a')
      var latlngs = [ //线中点的经纬度点
                [ 113.3203597222222, 33.74838222222222 ],
               [ 113.3207377777778, 33.74830944444445 ],
               [ 113.3209461111111, 33.7482750 ],
               [ 113.3211688888889, 33.74824138888889 ],
               [ 113.3219211111111, 33.74815083333333 ],
               [ 113.3221422222222, 33.74812416666666 ],
               [ 111.325266262, 31.74809750 ]
]
         
              
                console.log('d5s1a')
      
  //var circle =L.circleMarker([113.3203597222222,33.74838222222222],{radius:10000}).addTo(this.map);
     
//       var latlngs = [ //线中点的经纬度点
//                 [ 113.3203597222222, 33.74838222222222 ],
//                [ 113.3207377777778, 33.74830944444445 ],
//                [ 113.3209461111111, 33.7482750 ],
//                [ 113.3211688888889, 33.74824138888889 ],
//                [ 113.3219211111111, 33.74815083333333 ],
//                [ 113.3221422222222, 33.74812416666666 ],
//                [ 113.32236750, 33.74809750 ]
// ]
// var line = L.polyline(latlngs, {
//     color: 'red',//线的颜色
//     weight: 3 //线的粗细
// }).addTo(this.layerGroup.linesLayerGroup)
      let that = this;
      console.log('^^^^^^^^^^^^^^^^^^^^')
      // console.log(that.linesdata.features[0].geometry.type)
      // var latlngs = [
      //          [ 113.3203597222222, 33.74838222222222 ],
      //          [ 113.3207377777778, 33.74830944444445 ],
      //          [ 113.3209461111111, 33.7482750 ],
      //          [ 113.3211688888889, 33.74824138888889 ],
      //          [ 113.3219211111111, 33.74815083333333 ],
      //          [ 113.3221422222222, 33.74812416666666 ],
      //          [ 113.32236750, 33.74809750 ]
      //       ]
      // console.log(that.layerGroup.linesLayerGroup)      
      // console.log(L.polyline(latlngs, { style: that.biglinesStyle}).addTo(that.layerGroup.linesLayerGroup))
     
      let linesLayer = L.geoJson(that.linesdata, {
       filter:function(feature){
            switch (feature.geometry.type) {
                case 'LineString': return true; 
                case 'Point': return false;
            }
        },
        // id:feature.properties.name,
        style: function (feature) {
        return {
                weight:'1'
        };
        },
        onEachFeature:that.onEachFeature
        
      }).addTo(that.layerGroup.linesLayerGroup)
    


linesLayer.eachLayer(item=>{//遍历城市
        console.log(item)
      })


      that.map.fitBounds(linesLayer.getBounds());
      // fetch("./tt.json").then((response) => {
      //   response
      //     .json()
      //     .then((data) => {
      //       let lineLayer = L.geoJson(data, {
      //         style: that.biglinesStyle,
      //         onEachFeature: that.onEachFeature,
      //       }).addTo(that.layerGroup.linesLayerGroup);
      //       that.map.fitBounds(lineLayer.getBounds());

      //       let feaArray = [];
      //       for (const fea of data.features) {
      //         if (fea.properties.startLabel == "N9") {
      //           console.log("ok");
      //         }
      //         // multiLine
      //         let coords = fea.geometry.coordinates[0];
      //         let ls1 = that.getVerticalLine(coords[0], coords[1], 1, true);
      //         let ls2 = that.getVerticalLine(
      //           coords[coords.length - 2],
      //           coords[coords.length - 1],
      //           1,
      //           false
      //         );
      //         feaArray.push(ls1.line, ls2.line);

      //         that.produceLight(
      //           that.layerGroup.signalLayerGroup,
      //           fea.properties.startArray,
      //           ls1,
      //           fea.properties.startLocation,
      //           fea.properties.startLabel
      //         );
      //         that.produceLight(
      //           that.layerGroup.signalLayerGroup,
      //           fea.properties.endArray,
      //           ls2,
      //           fea.properties.endLocation,
      //           fea.properties.endLabel
      //         );
      //       }
      //       let fc = featureCollection(feaArray);
      //       L.geoJson(fc, {
      //         style: that.sizelinesStyle,
      //         onEachFeature: that.onEachFeature,
      //       }).addTo(that.layerGroup.insulatedLayerGroup);
      //     })
      //     .catch(function (error) {
      //       console.log("Request failed", error);
      //     });
      // });
    },

    
    //初始化站点
    initPoints() {
      let that = this;
      // var myIcon = L.divIcon({
      //   html: "申西站",
      //   className: "my-div-icon",
      //   iconSize: 120,
      // });
      // L.marker([33.749176, 113.331276], { icon: myIcon }).addTo(
      //   that.layerGroup.pointsLayerGroup
      // );
      var newa = that.linesdata.features.filter(function(feature){
              switch (feature.geometry.type) {
                case 'LineString': return false; 
                case 'Point': return true;
            }
      });
      newa.map((item) => {
       let iconSize = [16 + 16, 16];
        let iconAnchor = [0, 0];
        let imghtml = '<img class="my-div-image" style="" src="./yellow.png"/>';

        let myicon = new L.DivIcon({
          className: "my-div-iconl",
          iconSize: iconSize,
          iconAnchor: iconAnchor,
          html:
            '<div style="width:60' +
            'px;height:16px;">' +
            imghtml +
            '<span class="my-div-span" style="color:white;height:16px;line-height:16px">' +
            item.properties.name +
            "</span></div>",
        });
        const pointmarker = L.marker(
          [item.geometry.coordinates[1], item.geometry.coordinates[0]],
          {
            icon: myicon,
          }
        )
          .addTo(that.layerGroup.pointsLayerGroup)
          .on("click", function (e) {
            e.target.closePopup();
            if (that.map.getZoom() >= 18) {
              //e.target.bindPopup("<button type='button' onclick = 'addToCart(123)'>详情</button>") .openPopup();
              e.target.popupPlus(makerdetail, {
                props: {
                  prop1: this.obj,
                  prop2: "BBBBB",
                },
                popOptions: {
                  maxWidth: 500,
                  maxHeight: 500,
                  autoPan: true,
                  className: "testpop",
                },
              });
            } else {
              if(e.target.attrdata.properties.pointName=='十三矿站'){
                 that.map.setBearing(-84);
			           that.map.touchRotate.enable();
              }
              that.map.setView(e.latlng, 18);
            }
          });
        pointmarker.attrdata = item;

        //that.map.fitBounds(pointLayer.getBounds());
      });
    },
    //初始化信号灯
    initLight() {
      var myicon ;
      let that = this;
      var newa = that.linesdata.features.filter(function(feature){
              switch (feature.geometry.type) {
                case 'LineString': return false; 
                case 'Point': return true;
            }
      });
      newa.map((item) => {
       let iconSize = [16 + 16, 16];
        let iconAnchor = [0, 0];
        let imghtml = <circle id="SignalA" r="4" stroke-width="2" stroke="#404040" fill="#404040"/>
        if(item.properties.name!='insulating-joint')
        var name=item.properties.name
        else name=''
        let myicon = new L.DivIcon({
          className: "my-div-iconl",
          iconSize: iconSize,
          iconAnchor: iconAnchor,
          html:
            '<div style="width:60' +
            'px;height:16px;">' +
            '<span id="SignalA"           style="border-radius: 50% ;width: 10px ;display: inline-block;height: 10px;background-color:red"></span>'+
            '<span class="my-div-span" style="color:white;height:16px;line-height:16px;text-align: center;">' +
            name +
            "</span>      </div>",
        });
        const pointmarker = L.marker(
          [item.geometry.coordinates[1], item.geometry.coordinates[0]],
          {
            icon: myicon,
          }
        )
          .addTo(that.layerGroup.signalLayerGroup)
      })








//       console.log('^^^^^^^^^^^^^^^^^^^^')
//                console.log(that.layerGroup.signalLayerGroup)
//       console.log(that.linesdata.features[0].geometry.type)




//     var geojsonMarkerOptions = {

// radius: 0.56,

// fillColor: "#ff7800",

// color: "#000",

// weight: 1,

// opacity: 1,

// fillOpacity: 0.8

// };


//   that.linesdata.features.map((item) => {
//        let iconSize = [16 + 16, 16];
//         let iconAnchor = [0, 0];

//         myicon = new L.DivIcon({
//           className: "my-div-iconl",
//           iconSize: iconSize,
//           iconAnchor: iconAnchor,
//           html:
//             '<div style="width:60' +
//             'px;height:16px;">' +
//             '<span class="my-div-span" style="color:white;height:16px;line-height:16px">' +
//             item.properties.name +
//             "</span></div>",
//         });
//   })




// L.geoJSON(that.linesdata, {



// pointToLayer: function (feature, latlng){

// return L.circle(latlng, geojsonMarkerOptions);

// },
// alt: '123'

// }).addTo(that.layerGroup.signalLayerGroup);





      // let signalLayer = L.circle(that.linesdata, {
      //   filter:function(feature,latlng){
      //       switch (feature.geometry.type) {
      //           case 'LineString': return false; 
      //           case 'Point': return true;
      //       }
      //   },
      //   pointToLayer: function (feature, latlng){

      //     return L.circleMarker(latlng, geojsonMarkerOptions);

      //   },
      //    onEachFeature : that.onEachFeature
      //   // style: that.biglinesStyle
      // }).addTo(that.layerGroup.signalLayerGroup)
      // this.layerGroup.linesLayerGroup.addLayer(L.circle([113.3203597222222,33.74838222222222],{radius:10}))

      console.log(that.linesdata)
      // that.map.fitBounds(linesLayer.getBounds());
    },
    //初始化机车
    initLocomotive() {
      let that = this;
      // let log = pointPositionCalc(
      //   113.3253186806,
      //   33.74789592276,
      //   113.32498311279,
      //   33.74790379756,
      //   1000,
      //   2930.3326274353
      // );
      // console.log("坐标:", log);

      // L.marker(log).addTo(this.map);

      this.tempGp.tempNode.map(function (item) {
        if (item.myTag && item.myTag == 200) {
          // console.log("layer1:", item);
          // item.setStyle({ color: "black", fillcolor: "black" });
          // console.log("layer11:", item.getLatLngs()[0]);
          // var myMovingMarker = L.Marker.movingMarker(
          //   item.getLatLngs()[0],
          //   [
          //     2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
          //     2000, 2000, 2000,
          //   ],
          //   { autostart: true }
          // ).addTo(that.map);
          // myMovingMarker.start();
        } else if (item.myTag && item.myTag == 100) {
          // console.log("layer:", item.getLatLngs()[0]);
          // item.setStyle({ color: "red", fillcolor: "red" });
          // var myMovingMarker = L.Marker.movingMarker(
          //   item.getLatLngs()[0],
          //   [10000, 10000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000],
          //   { autostart: true }
          // ).addTo(that.map);
          // //myMovingMarker.start();
          // that.map.fitBounds(item.getBounds());
          // myMovingMarker.on("move", (res) => {
          //   // 监听点位移动事件 move
          //   //that.map.panTo([res.latlng.lat, res.latlng.lng]); //回调中会返回经纬度信息，点移动改变地图中心点
          //   //path.length > 1 && path.shift(); // 保持数组长度，避免过度push不断重新绘制之前的路径
          //   //path.push([res.latlng.lat, res.latlng.lng]); // 将数据push到数组中
          //   //L.polyline(path, { color: "#20a080", weight: 2 }).addTo(this.map); // 绘制线到地图图层
          // });
        }
      });
    },
    //初始化围栏
    initEnclosure() {
      let that = this;
      listBgeoinfo({ pageSize: 1000 }).then((response) => {
        if (response.code === 200) {
          that.addGeofencingToMap(
            that.layerGroup.geofencingLayerGroup,
            response.data.list
          );
        } else {
          that.msgError(response.msg);
        }
      });
    },
    //初始化人员
    initPersonnel() {},
    //绘制
    drawShape(e, type) {
      let that = this;
      that.closeAllDrawTools(that.drawArr);
      if (e == "Polygon") {
        that.closeDrawToolsStatus(that.drawTools.geofencingOptions, "polygon");
        that.drawTools.polyGeofencing.enabled()
          ? that.drawTools.polyGeofencing.disable()
          : that.drawTools.polyGeofencing.enable();
      } else if (e == "Rectangle") {
        that.closeDrawToolsStatus(
          that.drawTools.geofencingOptions,
          "rectangle"
        );
        that.drawTools.rectGeofencing.enabled()
          ? that.drawTools.rectGeofencing.disable()
          : that.drawTools.rectGeofencing.enable();
      } else if (e == "Circle") {
        that.closeDrawToolsStatus(that.drawTools.geofencingOptions, "circle");
        that.drawTools.circleGeofencing.enabled()
          ? that.drawTools.circleGeofencing.disable()
          : that.drawTools.circleGeofencing.enable();
      } else if (e == "Marker") {
        that.closeDrawToolsStatus(that.drawTools.geofencingOptions, "marker");
        that.drawTools.markerGeofencing.enabled()
          ? that.drawTools.markerGeofencing.disable()
          : that.drawTools.markerGeofencing.enable();
      }
      if (e == "edit") {
        that.closeDrawToolsStatus(that.drawTools.geofencingOptions, "edit");
        if (!that.drawTools.geofencingEdit.enabled()) {
          that.drawTools.editedGeoLayer.length > 0 &&
            that.drawTools.geofencingEdit.revertLayers();
        }
        that.drawTools.geofencingEdit.enabled()
          ? that.drawTools.geofencingEdit.disable()
          : that.drawTools.geofencingEdit.enable();
      }
      if (e == "delete") {
        that.layerGroup.geofencingLayerGroup.off("layerremove");
        if (that.layerGroup.geofencingLayerGroup.getLayers().length > 0) {
          that.closeDrawToolsStatus(that.drawTools.geofencingOptions, "delete");
          that.drawTools.geofencingDel.enabled()
            ? that.drawTools.geofencingDel.disable()
            : that.drawTools.geofencingDel.enable();
        } else {
          layer.msg("没有可以删除的目标");
        }
      }
      if (type == "1") {
        setDrawGeofencingToolTip();
        that.drawToolType = "geofencing";
      } else {
        setDrawlatlngToolTip();
        that.drawToolType = "pointlng";
      }
    },
    distanceMeasurement(e) {
      let that = this;
      setMeasureToolTip();
      that.closeAllDrawTools(that.drawArr);
      that.drawToolType = "measure";
      // 测面工具取消激活
      this.closeMeasureTools(
        this.drawTools.measureDisTool,
        this.drawTools.measureAreaTool
      );
      if (e == "measurement") {
        // 测距工具激活
        this.drawTools.measureDisTool.enable();
      } else if (e == "area") {
        // 测面工具激活
        this.drawTools.measureAreaTool.enable();
      } else if (e == "delete") {
        // 测面工具激活
        this.layerGroup.measureLayersGroup.clearLayers();
      }
    },
    /**
     * 添加电子围栏到地图
     * @param {L.FeatureGroup} featureGroup 电子围栏的图层组
     * @param {Array}          geofencing   电子围栏的数组
     */
    addGeofencingToMap(featureGroup, geofencing) {
      if (
        featureGroup instanceof L.FeatureGroup &&
        geofencing &&
        geofencing.length > 0
      ) {
        for (var i = geofencing.length - 1; i >= 0; i--) {
          if (geofencing[i].regionType === "circle") {
            featureGroup.addLayer(
              L.circle(
                L.latLng(getLatlngByString(geofencing[i].geofencingRegion)),
                {
                  radius: geofencing[i].radius,
                  color: "#FFFF00",
                  opacity: true,
                  dashArray: "10",
                  fill: false,
                  attribution: geofencing[i],
                }
              ).bindPopup(function (e) {
                return e.options.attribution.geoName;
              })
            );
          } else if (geofencing[i].regionType === "rectangle") {
            featureGroup.addLayer(
              L.rectangle(getLatlngByString(geofencing[i].geofencingRegion), {
                color: "#FFFF00",
                opacity: true,
                dashArray: "10",
                fill: false,
                attribution: geofencing[i],
              }).bindPopup(function (e) {
                return e.options.attribution.geoName;
              })
            );
          } else {
            featureGroup.addLayer(
              L.polygon(getLatlngByString(geofencing[i].geofencingRegion), {
                color: "#FFFF00",
                opacity: true,
                dashArray: "10",
                fill: false,
                attribution: geofencing[i],
              }).bindPopup(function (e) {
                return e.options.attribution.geoName;
              })
            );
          }
        }
        //map.fitBounds(featureGroup.getBounds());
      }
    },
    cancelDialog(dgtype) {
      if (dgtype == "geoDialog") {
        this.geoDialog = false;
        this.drawTools.geofencingEdit.disable();
      } else if (dgtype == "linesDialog") {
        this.linesDialog = false;
      } else if (dgtype == "locomotiveDialog") {
        this.locomotiveDialog = false;
      } else if (dgtype == "persionDialog") {
        this.persionDialog = false;
      }
    },
    confirmDialog(dgtype) {
      let that = this;
      that.geoDialog = false;
    },
    lineQuery() {
      this.linesDialog = true;
    },
    locomotiveTrack() {
      this.locomotiveDialog = true;
    },
    personnelTrack() {
      this.persionDialog = true;
    },
    /**
     * 关闭围栏绘制状态：显示、多边形、矩形、圆形、编辑、删除
     * @param  {Object} options JSON对象
     * @param  {String} type    几何类型
     * @return {undefined}      无返回值
     */
    closeDrawToolsStatus(options, type) {
      if (!options) {
        return;
      }
      if (options.polygon && type != "polygon") {
        options.polygon.obj && options.polygon.obj.disable();
      }
      if (options.rectangle && type != "rectangle") {
        options.rectangle.obj && options.rectangle.obj.disable();
      }
      if (options.circle && type != "circle") {
        options.circle.obj && options.circle.obj.disable();
      }
      if (options.edit && type != "edit") {
        options.edit.editLayer.length > 0 && options.edit.obj.revertLayers();
        options.edit.obj && options.edit.obj.disable();
      }
      if (options.delete && type != "delete") {
        options.delete.deleteLayer.off("layerremove");
        options.delete.obj && options.delete.obj.disable();
      }
    },
    /**
     * 关闭测量工具：测距、测面
     * @param  {L.Draw.Polyline} distanceTool 测距工具
     * @param  {L.Draw.Polygon}  areaTool     测面工具
     * @return {undefined}                    无返回值
     */
    closeMeasureTools(distanceTool, areaTool) {
      if (distanceTool instanceof L.Draw.Polyline) {
        distanceTool.disable();
      }
      if (areaTool instanceof L.Draw.Polygon) {
        areaTool.disable();
      }
      this.map.doubleClickZoom.disable();
    },
    /**
     * 关闭所有绘制工具：测量、物资查询、编辑围栏、编辑仓库、编辑单元
     * @param  {Array} drawArr 绘制工具数组
     * @return {undefined}     无返回值
     */
    closeAllDrawTools(drawArr) {
      if (drawArr && drawArr.length > 0) {
        for (var i = drawArr.length - 1; i >= 0; i--) {
          if (drawArr[i] instanceof L.EditToolbar.Edit) {
            drawArr[i].options.featureGroup.getLayer() > 0 &&
              drawArr[i].revertLayers();
          }
          drawArr[i].disable();
        }
      }
    },
    pointcancel() {
      this.linesDialog = false;
    },
    pointClick(item) {
      if (item.adcode == "100000") {
        this.map.setView([item.y, item.x], 11);
      } else {
        this.map.setView([item.y, item.x], 19);
      }
    },
    //geojson 回调函数
    onEachFeature(feature, layer) {
      let that = this;
      layer.id=feature.properties.name;
      layer.myTag = feature.properties.osm_id;
      layer.mawei = feature.
      properties.mawei;
      layer.cdno = feature.properties.cdno;
      layer.long = feature.properties.long;
      console.log(layer.id)
      layer.on("click", function (e) {
        if (that.map.getZoom() > 19)
          layer.bindPopup(
            "<button type='button' onclick = 'addToCart(" +
              layer._leaflet_id +
              ")'>Add to Cart</button>"
          );
      });
    },
    //小线段样式
    sizelinesStyle(feature) {
      return {
        fillColor: "white",
        weight: 1,
        color: "white",
        lineJoin: "bevel",
        lineCap: "butt",
      };
    },
    //大线段样式
    biglinesStyle(feature) {
      return {
        fillColor: "#556497",
        weight: 1,
        //fill:true,
        //opacity: 1,
        color: "#556497",
        //dashArray: "15, 10, 5, 10",
        // fillOpacity: 0.7,
        lineJoin: "bevel",
        lineCap: "butt",
      };
    },
    //改变某个围栏图层圈颜色
    changeGeofencingLayer(featureGroup, geoId) {
      if (featureGroup instanceof L.FeatureGroup) {
        featureGroup.eachLayer(function (layer) {
          layer.bindPopup("Hello");
        });
      }
    },
    getConfigResult(res) {
      console.log(res.data);
    },
    //改变某个人员标识颜色
    //改变某个信号灯图层颜色
    //改变某个线图层颜色
    //窗口变化
    changeDivHeight() {
      var h = document.body.clientHeight; //获取页面可见高度
      document.getElementById("map-container").style.height =
        h - 76 - 17 + "px";
      // 每次窗口大小改变后调用这个方法
      this.map.invalidateSize(true);
    },
    randColor() {
      let colors = ["red", "blue", "green", "black"];
      let idx = Math.ceil(Math.random() * 4);
      return colors[idx - 1];
    },
    // 角度划定在(-180，180]
    calcAngle(degree) {
      if (degree > 180) {
        return degree - 360;
      } else if (degree <= -180) {
        return degree + 360;
      }
      return degree;
    },
    getVerticalLine(startPt, endPt, halfLength, isVerticalPointAtStart) {
      let pt1 = point(startPt);
      let pt2 = point(endPt);
      let lineAngle = bearing(pt1, pt2);
      let startAngle = this.calcAngle(lineAngle + 90);
      let endAngle = this.calcAngle(lineAngle - 90);
      let verticalPoint = isVerticalPointAtStart ? pt1 : pt2;
      let first = destination(verticalPoint, halfLength * 0.001, startAngle, {
        units: "kilometers",
      });
      let last = destination(verticalPoint, halfLength * 0.001, endAngle, {
        units: "kilometers",
      });
      let lineDetail = {};
      lineDetail.line = lineString([
        first.geometry.coordinates,
        verticalPoint.geometry.coordinates,
        last.geometry.coordinates,
      ]);
      let antiLineAngle = this.calcAngle(lineAngle + 180);
      lineDetail.rl = destination(first, halfLength * 0.001, lineAngle, {
        units: "kilometers",
      });
      lineDetail.ru = destination(last, halfLength * 0.001, lineAngle, {
        units: "kilometers",
      });
      lineDetail.ll = destination(first, halfLength * 0.001, antiLineAngle, {
        units: "kilometers",
      });
      lineDetail.lu = destination(last, halfLength * 0.001, antiLineAngle, {
        units: "kilometers",
      });
      lineDetail.right = lineAngle;
      lineDetail.left = antiLineAngle;
      lineDetail.up = endAngle;
      lineDetail.down = startAngle;

      return lineDetail;
    },
    produceLight(lightLayer, lightArray, lsDetail, location, label) {
      let imghtml = "";
      for (const light of lightArray) {
        imghtml +=
          '<img class="my-div-image" style="" src="./' + light + '.png"/>';
      }
      let iconSize = [lightArray.length * 16 + 16, 16];
      let iconAnchor = [];
      let rotationAngle = 0;
      let rotationOrigin = "";
      switch (location) {
        case "lu":
          iconAnchor = [0, -2];
          rotationAngle = lsDetail.left - 90;
          rotationOrigin = "top left";
          break;
        case "ru":
          iconAnchor = [0, 16];
          rotationAngle = lsDetail.right - 90;
          rotationOrigin = "bottom left";
          break;
        case "ll":
          iconAnchor = [0, 16];
          rotationAngle = lsDetail.left - 90;
          rotationOrigin = "bottom left";
          break;
        case "rl":
          iconAnchor = [0, 0];
          rotationAngle = lsDetail.right - 90;
          rotationOrigin = "top left";
          break;
      }

      let myicon = new L.DivIcon({
        className: "my-div-iconl",
        iconSize: iconSize,
        iconAnchor: iconAnchor,
        html:
          '<div style="width:' +
          iconSize[0] +
          'px;height:16px;">' +
          imghtml +
          '<span class="my-div-span" style="color:white;height:16px;line-height:16px">' +
          label +
          "</span></div>",
      });
      let point = lsDetail[location];
      if (point) {
        L.marker([...point.geometry.coordinates].reverse(), {
          icon: myicon,
          rotationAngle: rotationAngle,
          // rotationOrigin: rotationOrigin,
        }).addTo(lightLayer);
      }
    },
  },
};
</script>
<style lang="less">
.map-container {
  width: 100%;
  height: calc(100%);
  z-index: 1;
  margin: auto;

  #map-container {
    width: 100%;
    height: calc(100%);
    z-index: 1;
    margin: auto;
    height: 550px;
    //background-color: black;
    background: rgb(1, 1, 20);
  }
}
@media screen and (max-width: 500px) {
  .el-message {
    min-width: 300px !important;
  }
}
@media screen and (max-width: 500px) {
  .el-message-box {
    width: 300px !important;
  }
}
@media screen and (max-width: 500px) {
  .el-dialog__wrapper .el-dialog {
    width: 300px !important;
    .el-dialog__body {
      padding: 10px 20px !important;
      .el-form-item__label {
        width: 68px !important;
      }
      .el-select,
      .el-input {
        width: 180px !important;
      }
    }
  }
}
</style>
<style>
.my-div-icon {
  font-size: 40px;
  color: white;
  width: 120px;
}
.my-div-image {
  width: 12px;
  height: 12px;
}
.my-div-span {
  font-size: 12px;
}
</style>
